package net.lab1024.smartadmin.module.support.quartz.task.run;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.qiniu.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.messagebuilder.MiniProgramNoticeMsgBuilder;
import net.lab1024.smartadmin.common.domain.ITask;
import net.lab1024.smartadmin.common.weixin.WxCpConfiguration;
import net.lab1024.smartadmin.common.weixin.WxMaConfiguration;
import net.lab1024.smartadmin.module.system.systemconfig.SystemConfigService;
import net.lab1024.smartadmin.module.system.systemconfig.constant.SystemConfigEnum;
import net.lab1024.smartadmin.module.weapp.message.MessageDao;
import net.lab1024.smartadmin.module.weapp.message.domain.entity.MessageEntity;
import net.lab1024.smartadmin.util.SmartDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * [  ]
 *
 * @author 五千
 * @version 1.0
 * @company 1024lab.net
 * @copyright (c) 2018 1024lab.netInc. All rights reserved.
 * @date 2021/3/16 0013 下午 14:26
 * @since JDK1.8
 */
@Slf4j
@Component("messageWayTask")
public class MessageWay implements ITask {

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private MessageDao messageDao;

    @Override
    public void execute(String paramJson) throws Exception {

        int type = Integer.parseInt(paramJson);
//        if(type == 1){
//            this.WxMaMessage(type);
//        }
//        else if(type == 2){
            this.WxCpMessage(type);
//        }
    }

    /**
     * 小程序订阅消息
     */
    private void WxMaMessage(Integer type) throws Exception {
        List<MessageEntity> messageEntityList = messageDao.selectWaitTask(type);
        String appid = systemConfigService.getCacheByKey(SystemConfigEnum.Key.WEAPP_APPID).getConfigValue();
        //多小程序切换
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        List<String> res_mes = new ArrayList<>();
        for(MessageEntity item : messageEntityList ) {
            MessageEntity oldEntity = messageDao.selectById(item.getId());
            WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
            wxMaSubscribeMessage.setTemplateId(item.getTemplateId());
            wxMaSubscribeMessage.setToUser(item.getToUser());
            List<WxMaSubscribeMessage.Data> data = new ArrayList<>();

            data = JSONObject.parseArray(item.getData(), WxMaSubscribeMessage.Data.class);

            wxMaSubscribeMessage.setData(data);
            wxMaSubscribeMessage.setPage(item.getPage());
            wxMaSubscribeMessage.setMiniprogramState("developer");
            try {
                wxService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
                item.setIsSuccess(1);
                item.setSendTime(new Date());
                item.setRebackMsg("发送成功");
            } catch (WxErrorException e) {
                item.setErrorNum(oldEntity.getErrorNum()+1);
                item.setSendTime(new Date());
                item.setRebackMsg(e.getMessage());
                res_mes.add(item.getToUser()+"=>"+e.getMessage());
            }

            messageDao.updateById(item);

        }
        //log.warn("{}-今天搬了{}块砖,paramJson:{}", SmartDateUtil.formatYMDHMS(new Date()), System.currentTimeMillis(), paramJson);
        if(res_mes.size() > 0){
            throw new Exception(StringUtils.join(res_mes.toArray(), "##"));
        }
    }

    private void WxCpMessage(Integer type) throws Exception {
        String appid = systemConfigService.getCacheByKey(SystemConfigEnum.Key.WEAPP_APPID).getConfigValue();
        List<MessageEntity> messageEntityList = messageDao.selectWaitTask(type);
        Integer agentid = Integer.valueOf(systemConfigService.getCacheByKey(SystemConfigEnum.Key.CP_AGENTID).getConfigValue());
        final WxCpService wxService = WxCpConfiguration.getCpService(agentid);
        List<String> res_mes = new ArrayList<>();
        for(MessageEntity item : messageEntityList ) {

            MiniProgramNoticeMsgBuilder minproBotice = new MiniProgramNoticeMsgBuilder();
            minproBotice.appId(appid);
            minproBotice.page(item.getPage());
            minproBotice.title(item.getTitle());
            minproBotice.description(item.getCreateTime().toString());
            Map<String,String> con = JSONObject.parseObject(item.getData(),new TypeReference<Map<String, String>>(){});
            minproBotice.contentItems(con);
            WxCpMessage wx = minproBotice.build();

            wx.setToUser(item.getToUser());
            try {
                wxService.getMessageService().send(wx);
                item.setIsSuccess(1);
                item.setSendTime(new Date());
                item.setRebackMsg("发送成功");
                messageDao.updateById(item);
            } catch (WxErrorException e) {
                item.setErrorNum(item.getErrorNum()+1);
                item.setSendTime(new Date());
                item.setRebackMsg(e.getMessage());
                res_mes.add(item.getToUser()+"=>"+e.getMessage());
            }

            messageDao.updateById(item);
        }

        if(res_mes.size() > 0){
            throw new Exception(StringUtils.join(res_mes.toArray(), "##"));
        }

    }
}
